/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-01 12:01:27
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-09-26 15:12:30
 * @FilePath: \keep_motion_api\models\sport\activity.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 活动模型
const activitySchema = new Schema({
  title: { type: String, required: true },
  type: {
    type: String,
    enum: ["challenge", "event", "tournament"]
  },
  start_date: Date,
  end_date: Date,
  participants: [{
    user_id: { type: Schema.Types.ObjectId, ref: 'User' },
    join_date: Date
  }],
  rules: String,
  rewards: [String],
  cover_image: String
});
activitySchema.statics.getSportActivities = async function (title, type, start_date, end_date, offset, limit) {
  try {
    const query = {};
    if (title) query.title = { $regex: escapeRegex(title), $options: 'i' };
    if (type) query.type = type;
    if (start_date) query.start_date = { $gte: new Date(start_date) };
    if (end_date) query.end_date = { $lte: new Date(end_date) };
    const rows = await this.find(query).skip(offset).limit(limit).exec();
    const total = await this.countDocuments(query);
    return { rows: rows.map(item => ({...item.toObject(), participantNums: item.participants.length})), total };
  } catch (error) {
    throw new Error('查询运动活动失败');
  }
}
activitySchema.statics.createSportActivities = async function (data) {
  try {
    const activity = new this(data);
    return await activity.save();
  } catch (error) {
    throw new Error('创建运动活动失败');
  }
}
activitySchema.statics.updateSportActivities = async function (id, data) {
  try {
    const activity = await this.findByIdAndUpdate(id, data, { new: true });
    if (!activity) throw new Error('运动活动不存在');
    return activity;
  } catch (error) {
    throw new Error('更新运动活动失败');
  }
}
activitySchema.statics.getActivityParticipants = async function (id) {
  try {
    const activity = await this.findById(id);
    if (!activity) throw new Error('运动活动不存在');
    if (activity.participants.length === 0) return {total: 0, rows: []};
    const { User } = require('../user')
    const ids = activity.participants.map(item => item.user_id);
    console.log(ids)
    const query = {_id: {$in: ids }}
    const participants = await User.find(query);
    console.log(participants)
    if (!participants) throw new Error('查询运动活动参与人失败');
    return {total: participants.length, rows: participants};
  } catch (error) {
    throw new Error('查询运动活动参与人失败');
  }
}
module.exports = mongoose.model('Activity', activitySchema);
